Namespace Result
    Public Class TxtRsWriter
        Inherits RsWriter
        Public WriteHeader As Boolean = True
        Public Append As Boolean = True
        Public Delimiter As String = vbTab
        Public Encoding As System.Text.Encoding = System.Text.Encoding.Default
        Public FinalLine As Boolean = True

        Private Writer As IO.StreamWriter

        Public Sub New(ByVal Source As ADODB.Recordset, ByVal Target As String)
            MyBase.New(Source, Target)
        End Sub

        Public Overrides Function Execute() As Long
            Writer = FileIO.FileSystem.OpenTextFileWriter(Target, Append, Encoding)
            If WriteHeader Then DoWriteHeader()
            Return DoWriteValues()
        End Function

        Private Sub DoWriteHeader()
            Dim ShouldWriteDelimiter As Boolean = False
            For Each f As ADODB.Field In Source.Fields
                If ShouldWriteDelimiter Then Writer.Write(Delimiter)
                Writer.Write(f.Name)
                ShouldWriteDelimiter = True
            Next
        End Sub

        Private Function DoWriteValues() As Long
            Dim ShouldWriteLine As Boolean = WriteHeader
            Dim ShouldWriteDelimiter As Boolean
            Dim LineCount As Long = 0

            While Not Source.EOF
                If ShouldWriteLine Then Writer.WriteLine()
                ShouldWriteLine = True
                ShouldWriteDelimiter = False
                LineCount += 1

                For Each f As ADODB.Field In Source.Fields
                    If ShouldWriteDelimiter Then Writer.Write(Delimiter)
                    Dim valueString As String = FormattedValueString(f)
                    Writer.Write(valueString)
                    ShouldWriteDelimiter = True
                Next
                Source.MoveNext()
                Threading.Thread.Sleep(1)
            End While
            If FinalLine Then Writer.WriteLine()
            Writer.Close()
            Return LineCount
        End Function

    End Class
End Namespace
